package com.sevenluo.netty.learn.server.codec.handler;

import com.sevenluo.netty.learn.common.Operation;
import com.sevenluo.netty.learn.common.RequestMessage;
import com.sevenluo.netty.learn.common.auth.AuthOperation;
import com.sevenluo.netty.learn.common.auth.AuthOperationResult;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: 程序员七哥
 * @date: 2022-02-03
 * @description: 自定义授权管理
 */
@ChannelHandler.Sharable
@Slf4j
public class AuthHandler extends SimpleChannelInboundHandler<RequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RequestMessage requestMessage) throws Exception {

        try {
            Operation operation = requestMessage.getMessageBody();
            if (operation instanceof AuthOperation) {
                AuthOperation authOperation = AuthOperation.class.cast(operation);
                AuthOperationResult authOperationResult = authOperation.execute();
                if (authOperationResult.isPassAuthor()) {
                    log.info("auth is pass");
                } else {
                    log.error("auth is fail");
                    channelHandlerContext.close();
                }
            } else {
                log.error("expect first message is auth");
                channelHandlerContext.close();
            }
        } catch (Exception e) {
            log.error("error happen");
            channelHandlerContext.close();
        } finally {
            channelHandlerContext.pipeline().remove(this);
        }
    }
}
